<template>
  <div class="iotList">
    <search-block>
      <template slot="button">
        <el-button type="primary" @click="search(true)">查询</el-button>
        <el-button type="primary" @click="addIot">添加设备</el-button>
      </template>
      <el-form inline :model="model" label-width="100px" @submit.native.prevent v-if="activeName === '1'">
        <el-form-item label="设备类型:">
          <y-code-select
            v-model="model.type"
            clearable
            dict="IOT_DEVICE_TYPE"></y-code-select>
        </el-form-item>
      </el-form>
    </search-block>
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="ZERO设备" name="1">
        <y-table
          ref="table2"
          border
          pagination
          :getDataWay="getDataWay2"
          :columns="columns2"
        >
          <el-table-column slot="y-oper" label="操作" align="center" header-align="center" :width="isTestVideo ? 210 : 150">
            <template v-slot="scope">
              <div class="table-buttons">
                <el-button v-if="isTestVideo" type="primary" size="mini" @click="getUri(scope.row)">视频</el-button>
                <el-button type="primary" size="mini" @click="editIot(scope.row)">编辑</el-button>
                <el-popconfirm
                  title="是否确认删除该设备？"
                  @confirm="delIot(scope.row)">
                  <el-button slot="reference" type="danger" size="mini">删除</el-button>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </y-table>
      </el-tab-pane>
      <el-tab-pane label="阿里云设备" name="2">
        <y-table
          ref="table1"
          border
          pagination
          :getDataWay="getDataWay"
          :columns="columns"
        >
          <el-table-column slot="status" label="是否上线" align="center" header-align="center">
            <template v-slot="scope">
              <el-popconfirm
                :title="scope.row.status === '0' ? '是否确认下线该设备？' : '是否确认上线该设备？'"
                @confirm="() => {
                  if(scope.row.status === '0') lockDevice(scope.row)
                  else unlockDevice(scope.row);
                }">
                <el-switch
                  disabled
                  slot="reference"
                  v-model="scope.row.status"
                  active-value="0"
                  inactive-value="1"></el-switch>
              </el-popconfirm>
            </template>
          </el-table-column>
          <el-table-column slot="y-oper" label="操作" align="center" header-align="center" :width="isTestVideo ? 210 : 150">
            <template v-slot="scope">
              <div class="table-buttons">
                <el-button v-if="isTestVideo" type="primary" size="mini" @click="getUri(scope.row)">视频</el-button>
                <el-button type="primary" size="mini" @click="editIot(scope.row)">编辑</el-button>
                <el-popconfirm
                  title="是否确认删除该设备？"
                  @confirm="delIot(scope.row)">
                  <el-button slot="reference" type="danger" size="mini">删除</el-button>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </y-table>
      </el-tab-pane>
      
    </el-tabs>
    <y-form
      v-model="forms.formModel"
      :visible.sync="forms.showForm"
      :title="forms.formTypeTitle[forms.formsType]"
      destroy-on-close
      force-inner-scroll
      width="50%"
      :form-attrs="forms.formAttrs"
      :columns="forms.formColumns"
      @ensure="ensureModel">
    </y-form>
    <y-form
      v-model="forms2.formModel"
      :visible.sync="forms2.showForm"
      :title="forms2.formTypeTitle[forms2.formsType]"
      destroy-on-close
      force-inner-scroll
      width="50%"
      :form-attrs="forms2.formAttrs"
      :columns="forms2.formColumns"
      @ensure="ensureModel">
    </y-form>
    <el-dialog
      class="video-dialog force-inner-scroll"
      :visible.sync="videoForms.show"
      width="800px"
      @closed="closeVideo">
      <template v-if="videoForms.uri">
        <iframe
          v-if="activeName === '1'"
          :src="'/video/camera.html?addr=' + encodeURIComponent(videoForms.uri)"
          width="100%"></iframe>
        <iframe
          v-if="activeName === '2'"
          :src="videoForms.uri"
          width="100%"></iframe>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "iotList",
  inject: ['pattern'],
  computed:{
    getDataWay(){
      return{
        dataType: 'url',
        data: this.$api.self.iotList,
        param: this.model
      }
    },
    getDataWay2(){
      return{
        dataType: 'url',
        data: this.$api.self.ysPage,
        param: this.model
      }
    },
    isTestVideo(){
      return this.$route.query.admin !== undefined;
    }
  },
  data(){
    return{
      activeName: '1',
      model:{
        type: '',
      },
      columns: [{
        label: "设备名称",
        prop: "deviceName"
      },{
        label: "设备类型",
        prop: "type"
      },{
        label: "上线",
        prop: "status",
        template: true
      }],
      columns2: [{
        label: "直播间名称",
        prop: "name"
      }],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加设备',
          'EDIT': '编辑设备'
        },
        formModel:{
          iotId: '',
          deviceName: '',
          type: '',
          accessKeyId: '',
          accessKeySecret: '',
          domain: '',
          instanceId: '',
          productCode: '',
          regionId: '',
          scheme: ''
        },
        currentForm: null,
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            iotId: [{required: true, message: "请输入设备id", trigger: "blur"}],
            deviceName: [{required: true, message: "请输入设备名称", trigger: "blur"}],
            type: [
              {required: true, message: "请选择设备类型", trigger: "change"}
            ]
          }
        },
        formColumns:[
          {
            label: "设备ID",
            prop: "iotId",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 32,
                showWordLimit: true
              }
            }
          },
          {
            label: "设备名称",
            prop: "deviceName",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 30,
                showWordLimit: true
              }
            }
          },
          {
            label: "设备类型",
            prop: "type",
            comp:{
              compType: 'YCodeSelect',
              attrs: {
                dict: 'IOT_DEVICE_TYPE'
              }
            }
          },
          {
            label: "阿里云ID",
            prop: "accessKeyId",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 32,
                showWordLimit: true
              }
            }
          },
          {
            label: "阿里云Secret",
            prop: "accessKeySecret",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 32,
                showWordLimit: true
              }
            }
          },
          {
            label: "请求域名",
            prop: "domain",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 60,
                showWordLimit: true
              }
            }
          },
          {
            label: "实例ID",
            prop: "instanceId",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 32,
                showWordLimit: true
              }
            }
          },
          {
            label: "产品Code",
            prop: "productCode",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 32,
                showWordLimit: true
              }
            }
          },
          {
            label: "设备地域ID",
            prop: "regionId",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 32,
                showWordLimit: true
              }
            }
          },
          {
            label: "视频类型",
            prop: "scheme",
            comp:{
              compType: 'YCodeSelect',
              attrs: {
                dict: 'IOT_SCHEME'
              }
            }
          }
        ],
      },
      forms2:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加设备',
          'EDIT': '编辑设备'
        },
        formModel:{
          name: '',
          url: ''
        },
        currentForm: null,
        showForm: false,
        formAttrs:{
          labelWidth: '120px',
          rules: {
            name: [{required: true, message: "请输入直播间名称", trigger: "blur"}],
            url: [{required: true, message: "请输入直播间地址", trigger: "blur"}]
          }
        },
        formColumns:[
          {
            label: "直播间名称",
            prop: "name",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 30,
                showWordLimit: true
              }
            }
          },
          {
            label: "直播间地址",
            prop: "url",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 100,
                showWordLimit: true
              }
            }
          }
        ]
      },
      videoForms:{
        uri: '',
        show: false
      }
    }
  },
  methods:{
    resetForm(){
      const forms = this.activeName === '1' ? this.forms2 : this.forms;
      Object.keys(forms.formModel).map(key => {
        forms.formModel[key] = forms.currentForm ? forms.currentForm[key] : '';
      })
    },
    addIot(){
      const forms = this.activeName === '1' ? this.forms2 : this.forms;
      forms.formsType = 'ADD';
      forms.currentForm = null;
      this.resetForm();
      forms.showForm = true;
    },
    search(jumpToFirst){
      this.$refs['table' + this.activeName].loadData(this.model, jumpToFirst);
    },
    getUri(row){
      if(this.activeName === '1'){
        this.videoForms.uri = row.url;
        this.videoForms.show = true;
      }else{
        this.$yAxios({
          url: this.$api.self.iotURI,
          data:{
            ids: [row.id]
          }
        }, info => {
          if(Array.isArray(info) && info.length){
            this.videoForms.uri = info[0].uri.replace('https://www.imflea.cn', location.protocol + '//' + location.host);
            this.videoForms.show = true;
          }
        })
        
      }
    },
    editIot(row){
      console.log(row,2222)
      const forms = this.activeName === '1' ? this.forms2 : this.forms;
      forms.formsType = 'EDIT';
      forms.currentForm = row;
      this.resetForm();
      forms.showForm = true;
    },
    delIot(row){
      const url = this.activeName === '1' ? this.$api.self.removeYs : this.$api.self.removeIot ;
      const event = this.activeName === '1' ? 'refreshYsList' : 'refreshIotList';
      this.$yAxios({
        url,
        data:{
          ids: [row.id]
        }
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
        this.$bus.$emit(event);
      })
    },
    lockDevice(row){
      this.$yAxios({
        url: this.$api.self.iotStatus,
        data:{
          id: row.id,
          status: '1'
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功下线设备【${row.deviceName}】`
        });
        row.status = '1'
        this.$bus.$emit('refreshIotList');
      });
    },
    unlockDevice(row){
      this.$yAxios({
        url: this.$api.self.iotStatus,
        data:{
          id: row.id,
          status: '0'
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功上线设备【${row.deviceName}】`
        });
        row.status = '0';
        this.$bus.$emit('refreshIotList');
      });
    },
    ensureModel(form){
      const forms = this.activeName === '1' ? this.forms2 : this.forms;
      let newForm;
      if(forms.formsType === 'EDIT'){
        newForm = Object.assign({}, forms.currentForm, form);
      }else{
        newForm = this.activeName === '1' ? form : Object.assign({ status: '1' }, form);
      }
      this.$yAxios({
        url: this.activeName === '1' ? this.$api.self.saveYs : this.$api.self.saveIot ,
        data: newForm
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search(forms.formsType === 'ADD');
        this.$bus.$emit(this.activeName === '1' ? 'refreshYsList' : 'refreshIotList');
      })
    },
    closeVideo(){
      this.videoForms.uri = '';
    }
  }
}
</script>

<style scoped lang="less">
.iotList{
  >.SearchBlock{
    display: inline-flex;
    position: relative;
    z-index: 1;
  }
  >.el-tabs{
    margin-top: -41px;
    /deep/ .el-tabs__nav{
      float: right;
    }
  }
}
.video-dialog{
  /deep/.el-dialog__body{
    height: 500px;
    iframe{
      height: calc(100% - 4px);
      border: none;
    }
  }
}
</style>